layui.config({
	base : baseUrl +"/static/js/common/"
}).extend({
	"baseTable" : "baseTable"
})
var editId,curUser;
layui.use(['form','layer',"baseTable"],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.baseTable;
    
         curUser =  $.parseJSON(sessionStorage.getItem("curUser"));
         
         
         
    //用户列表
    var tableIns = table.render({
        elem: '#userList',
        url : baseUrl+'/sys/user/list',
        cellMinWidth : 95,
        id : "userListTable",
        cols : [[
            {field:"1", type: "checkbox", width:50},
            {field: 'userId', title: '用户ID',hide:true, minWidth:100, align:"center"},
            {field: 'username', title: '用户名', minWidth:100, align:"center"},
            {field: 'roleList', title: '角色名称', align:'center',templet:function(d){
            	if(d.userId == 1){
            		return '超级管理员';
            	}else{
            		if(d.roleList == null || d.roleList =='')
            			return '无';
            		return d.roleList;
            	}
            }},
            {field: 'email', title: '用户邮箱', minWidth:200, align:'center',templet:function(d){
                return '<a class="layui-blue" href="mailto:'+d.email+'">'+d.email+'</a>';
            }},
            {field: 'mobile', title: '电话号码',  align:'center'},
            {field: 'status', title: '用户状态',  align:'center',templet:function(d){
                return d.status == 1 ? '<label class="layui-btn-green layui-btn-xs layui-btn" style="cursor:auto">'+"正常使用"+'</label>' : '<label class="layui-bg-red layui-btn-xs layui-btn" style="cursor:auto">'+"限制使用"+'</label>';
            }},
            {field: 'createTime', title: '创建时间', align:'center',minWidth:150},
            {title: '操作', minWidth:175, templet:'#userListBar',align:"center"}
        ]],
        done:function(){
        	//init();
        	if(curUser.userId != 1){
        		$(".del,.delAll_btn").remove();
        	}
        	
        	
        }
    });
    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click",function(){
       
        	tableIns.reload({
        		where: {
                    username: $(".searchVal").val()  //搜索的关键字
                }
        	})
        
    });

    //添加用户
    function addUser(edit){
        var index = layui.layer.open({
            title : "添加用户",
            type : 2,
            content : getUrl("userAdd.html"),
            success : function(layero, index){
              setTimeout(function(){
                    layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
        layui.layer.full(index);
        window.sessionStorage.setItem("index",index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }
    
    function editUser(edit){
    	editId = edit.userId;
        var index = layui.layer.open({
            title : "编辑用户",
            type : 2,
            content : getUrl("userEdit.html"),
            success : function(layero, index){
              setTimeout(function(){
                    layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                },500)
            }
        })
        layui.layer.full(index);
        window.sessionStorage.setItem("index",index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize",function(){
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }
    
    $(".addUsers_btn").click(function(){
        addUser();
    })

    $(".reset_btn").click(function(){
    	  var checkStatus = table.checkStatus('userListTable'),
            data = checkStatus.data,
            userIds = [];
    	  if(data.length > 0) {
              for (var i in data) {
              	userIds.push(data[i].userId);
              }
              layer.confirm('确定重置选中的用户？', {icon: 3, title: '提示信息'}, function (index) {
              	ajaxRequest({
              		url:'/sys/user/resetPwd',
              		param:userIds,
              		success:function(){
              			baseAlert("重置成功，密码为123456");
              		}
              	})
              	
              })
          }else{
              layer.msg("请选择需要重置的用户");
          }
    })
    
    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('userListTable'),
            data = checkStatus.data,
            userIds = [];
        if(data.length > 0) {
            for (var i in data) {
            	userIds.push(data[i].userId);
            }
            layer.confirm('确定删除选中的用户？', {icon: 3, title: '提示信息'}, function (index) {
            	ajaxRequest({
            		url:'/sys/user/delete',
            		param:userIds,
            		success:function(){
            			table.reload("userListTable");
            			baseAlert("删除成功")
            		}
            	})
            	layer.close(index);
            	
            })
        }else{
            layer.msg("请选择需要删除的用户");
        }
    })

    //列表操作
    table.on('tool(userList)', function(obj){
        var layEvent = obj.event,
            data = obj.data;
        if(layEvent === 'edit'){ //编辑
            editUser(data);
        }else if(layEvent === 'usable'){ //启用禁用
            var _this = $(this),
                usableText = "是否确定禁用此用户？",
                status = 0,
                btnText = "已禁用";
            if(_this.text()=="已禁用"){
                usableText = "是否确定启用此用户？",
                btnText = "已启用";
                status = 1;
            }
            layer.confirm(usableText,{
                icon: 3,
                title:'系统提示',
                cancel : function(index){
                    layer.close(index);
                }
            },function(index){
            	ajaxRequest({
            		url:'/sys/user/unable',
            		param:{userId:data.userId,status:status},
            		success:function(){
            			obj.update({
            				'status': status
            				});
            			_this.text(btnText).toggleClass("layui-btn-warm").toggleClass("layui-btn-danger");
            		}
            	})
                layer.close(index);
            },function(index){
                layer.close(index);
            });
        }else if(layEvent === 'del'){ //删除
            layer.confirm('确定删除此用户？',{icon:3, title:'提示信息'},function(index){
            	ajaxRequest({
            		url:'/sys/user/delete',
            		param:[data.userId],
            		success:function(){
            			table.reload("userListTable");
            			baseAlert("删除成功");
            		}
            	})
            	layer.close(index);
            	
            });
        }
    });

   
})
